<template>
  <div class="sso-login">
    <h3>正在通过单点登录跳转，请稍候...</h3>
  </div>
</template>

<script setup>
import {onMounted} from 'vue'
import useUserStore from '@/store/modules/user'
import {useRoute, useRouter} from "vue-router";

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

const redirect = ref(undefined)

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

onMounted(() => {
  // 获取 URL 参数
  const urlParams = new URLSearchParams(window.location.search)
  const ticket = urlParams.get('ticket')
  const authCode = urlParams.get('authCode')
  const loginType = window.location.pathname.includes('/perLogin') ? 'perLogin' : 'corLogin'

  if (!ticket || !authCode) {
    alert('缺少 ticket 或 authCode 参数')
    router.push('/login')
    return
  }

  // 构造请求 URL
  const ssoLoginUrl = `/sso/${loginType}?ticket=${ticket}&authCode=${authCode}`

  /*ssoLogin(ssoLoginUrl).then(data => {
    if (data.code === 200 && data.token) {
      // 存储 token 到 localStorage
      localStorage.setItem('token', data.token)

      // 手动设置到 pinia store 的 token 字段
      userStore.$patch({ token: data.token })

      // 获取用户信息并跳转首页
      return userStore.getInfo().then(() => {
        router.push('/')
      })
    } else {
      alert('登录失败：' + (data.msg || '未知错误'))
      router.push('/login')
    }
  })*/
  // 调用action的登录方法
  userStore.ssoLogin(ssoLoginUrl).then(() => {
    const query = route.query
    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
      if (cur !== "redirect") {
        acc[cur] = query[cur]
      }
      return acc
    }, {})
    router.push({ path: redirect.value || "/", query: otherQueryParams })
  }).catch(() => {
    loading.value = false
    // 重新获取验证码
    if (captchaEnabled.value) {
      getCode()
    }
  })
})
</script>

<style scoped>
.sso-login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  font-size: 18px;
}
</style>
